<template>
    <!-- 供应商变更入库-新增 -->
    <div class="e-form">
        <div class="tabs">
            <div class="tabs-title">基本信息</div>
            <div style="width: 100%" class="form">
                <el-form
                    :model="formData"
                    ref="formData"
                    :rules="rules"
                    label-width="150px"
                >
                    <BillTop title="供应商变更入库新增" @cancel="handleClose"></BillTop>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item
                                label="统一社会信用代码"
                                prop="creditCode"
                            >
                                {{ formData.creditCode }}
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item
                                label="供应商名称"
                                prop="supplierName"
                            >
                                <el-input
                                    v-model="formData.supplierName"
                                    placeholder="请填写"
                                ></el-input>
                                <img
                                    v-if="
                                      isLoad &&
                                        oldEditData.supplierName !=
                                            formData.supplierName
                                    "
                                    class="img-style"
                                    src="@/assets/biangeng.png"
                                    alt=""
                                />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="24">
                            <el-form-item
                                label="供应商类型"
                                prop="supplierTypeKey"
                            >
                                <el-checkbox
                                    style="margin: 0px 30px 5px 0px"
                                    :indeterminate="isIndeterminate"
                                    v-model="checkAll"
                                    @change="handleCheckAllChange"
                                >
                                    全选
                                </el-checkbox>
                                <el-checkbox-group
                                    v-model="formData.supplierTypeKey"
                                    @change="handleCheckedCitiesChange"
                                >
                                    <el-checkbox
                                        v-for="item in typeList"
                                        :key="item.kvId"
                                        :label="item.kvKey"
                                        :value="item.kvId"
                                    ></el-checkbox>
                                </el-checkbox-group>
                                <img
                                    v-if="isSubcontractorTypeKey"
                                    class="img-style"
                                    src="@/assets/biangeng.png"
                                    alt=""
                                />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item
                                label="注册地址"
                                prop="registerAddInfo"
                            >
                                <SelectAddr
                                    v-model="formData.registerAddInfo"
                                    @getLabel="getAddrLabel"
                                    lazy
                                    showCountry
                                    style="width: 100%"
                                ></SelectAddr>
                                <!-- 详细地址 -->
                                <img
                                    v-if="
                                       isLoad &&
                                        oldEditData.registerAddInfo !=
                                            formData.registerAddInfo
                                    "
                                    class="img-style"
                                    src="@/assets/biangeng.png"
                                    alt=""
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12"></el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="联系电话" prop="contactTel">
                                <el-input
                                    placeholder="请填写"
                                    v-model="formData.contactTel"
                                ></el-input>
                                <img
                                    v-if="
                                      isLoad &&
                                        oldEditData.contactTel !=
                                            formData.contactTel
                                    "
                                    class="img-style"
                                    src="@/assets/biangeng.png"
                                    alt=""
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="法人代表" prop="deputy">
                                <el-input
                                    placeholder="请填写"
                                    v-model="formData.deputy"
                                ></el-input>
                                <img
                                    v-if="
                                        isLoad &&
                                        oldEditData.deputy != formData.deputy
                                    "
                                    class="img-style"
                                    src="@/assets/biangeng.png"
                                    alt=""
                                />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="传真" prop="fax">
                                <el-input
                                    placeholder="请填写"
                                    v-model="formData.fax"
                                ></el-input>
                                <img
                                    v-if="
                                      isLoad &&
                                        oldEditData.fax != formData.fax
                                    "
                                    class="img-style"
                                    src="@/assets/biangeng.png"
                                    alt=""
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item
                                label="注册资本（万元）"
                                prop="registerCapital"
                            >
                                <el-input
                                    placeholder="请填写"
                                    v-model="formData.registerCapital"
                                    v-enterFloat2
                                ></el-input>
                                <img
                                    v-if="
                                       isLoad &&
                                        oldEditData.registerCapital !=
                                            formData.registerCapital
                                    "
                                    class="img-style"
                                    src="@/assets/biangeng.png"
                                    alt=""
                                />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="纳税类别：" prop="taxTypeName">
                                <el-radio-group
                                    @change="radioChange($event)"
                                    v-model="formData.taxTypeName"
                                >
                                    <el-radio
                                        v-for="item in payTaxesTypeList"
                                        :key="item.kvId"
                                        :label="item.kvKey"
                                        :disabled="item.disabled"
                                        :value="item.kvValue"
                                    ></el-radio>
                                </el-radio-group>
                                <img
                                    v-if="
                                       isLoad &&
                                        oldEditData.taxTypeName !=
                                            formData.taxTypeName
                                    "
                                    class="img-style"
                                    src="@/assets/biangeng.png"
                                    alt=""
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="邮箱" prop="email">
                                <el-input
                                    placeholder="请填写"
                                    v-model="formData.email"
                                ></el-input>
                                <img
                                    v-if="
                                       isLoad &&
                                        oldEditData.email != formData.email
                                    "
                                    class="img-style"
                                    src="@/assets/biangeng.png"
                                    alt=""
                                />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="增值税一般纳税人资格查询">
                                <a
                                    href="https://etax.sichuan.chinatax.gov.cn/"
                                    target="_blank"
                                >
                                    查询
                                </a>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="邮编" prop="postCode">
                                <el-input
                                    placeholder="请填写"
                                    v-model="formData.postCode"
                                ></el-input>
                                <img
                                    v-if="
                                       isLoad &&
                                        oldEditData.postCode !=
                                            formData.postCode
                                    "
                                    class="img-style"
                                    src="@/assets/biangeng.png"
                                    alt=""
                                />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="信用信息查询">
                                <a
                                    href="http://www.gsxt.gov.cn/index.html"
                                    target="_blank"
                                >
                                    查询
                                </a>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="四川住房城乡建设厅信息查询">
                                <a
                                    href="http://202.61.88.188/xxgx/index.aspx"
                                    target="_blank"
                                >
                                    查询
                                </a>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="是否为境外单位">
                                <el-switch
                                    :width="60"
                                    v-model="formData.isAbroadUnit"
                                    class="main-el-switch"
                                    active-color="#13ce66"
                                    inactive-color="#D2D2D2"
                                    active-value="1"
                                    inactive-value="0"
                                    active-text="是"
                                    inactive-text="否"
                                >
                                </el-switch>
                                <img
                                    v-if="
                                       isLoad &&
                                        oldEditData.isAbroadUnit !=
                                            formData.isAbroadUnit
                                    "
                                    class="img-style"
                                    src="@/assets/biangeng.png"
                                    alt=""
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="管理单位">
                                {{ formData.manageOrgName }}
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="信用等级">
                                <span>
                                    {{
                                        formData.creditLevel == '0'
                                            ? '待定'
                                            : formData.creditLevel == '1'
                                            ? 'A'
                                            : formData.creditLevel == '2'
                                            ? 'B'
                                            : formData.creditLevel == '3'
                                            ? 'C'
                                            : formData.creditLevel == '4'
                                            ? 'D'
                                            : formData.creditLevel == '5'
                                            ? 'S'
                                            : ''
                                    }}</span
                                >
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="状态">
                                {{ statusLable(formData.state) }}
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-form-item label="录入人">
                             {{formData.founderName }}
                        </el-form-item>
                    </el-row>
                </el-form>
            </div>
        </div>
        <div class="buttons">
            <el-button
                type="primary"
                style="background: #2e61d7"
                @click="save()"
            >
                保存
            </el-button>
            <el-button @click="cancel()">取消</el-button>
        </div>
    </div>
</template>

<script>
import SelectAddr from '@/components/common/addrComp'
import Supplier from '@/api/OutsourcingartyAdmin/supplier/supplier'
import supplierChange from '@/api/OutsourcingartyAdmin/supplier/supplierChange'
import '@/utils/jquery.scrollTo.min'
import { mapMutations } from 'vuex'
// import { showSuccessPop } from '@/utils/common'
import { getOrgById, getOrgByParentId } from '@/api/base/system'
import call from '@/api/OutsourcingartyAdmin/getAllType.js'
import {
    creditCodeVerification,
    isPhone,
    isEmail,
    isName,
    isPostCode,
    isFax
} from '@/utils/rules'
export default {
    data () {
        return {
            //表单数据
            formData: {
                creditCode: '', //统一社会信用代码
                supplierName: '', //供包商名称
                type: '', //类型
                deputy: '', //法人代表
                registerAddInfo: '', //注册详细地址
                contactTel: '', //联系电话
                registerCapital: '', //注册资本
                fax: '', //传真
                email: '', //邮箱
                taxType: '', //纳税类别
                postCode: '', //邮编
                manageOrgName: '', //管理单位
                isAbroadUnit: '', //是否为境外单位
                enteringPerson: '', //录入人
                enteringDate: '', //录入时间
                creditLevel: '2', //信用等级
                state: 0, //状态
                supplierTypeValue: [], //供应商名称
                supplierTypeKey: [], //供应商id
                taxTypeName: '', //纳税类别名字
                taxTypeValue: '', //纳税类别id
                billDate: '', //单据时间
                businessScopeId: '', //主营范围id
                businessScopeName: '', //主营范围
                changeState: 1, //变更状态
                contactName: '', //联系人
                id: '',
                isEnabled: 0, //境外单位
                isQualified: 0, //是否启用
                kdId: '',
                manageOrgId: '',
                nullifyCreated: '',
                nullifyCreator: '',
                nullifyCreatorId: '',
                nullifyDescription: '',
                nullifyReason: '',
                orgId: '',
                orgName: '',
                projectLeader: '',
                qualificationLevelId: '',
                qualificationLevelName: '',
                registerAddCity: '',
                registerAddDistrict: '',
                registerAddProvince: '',
                remark: '',
                source: 0,
                sourceId: '', //原单id
                supplierId: '',
                supplierNo: '',
                supplierTimestamp: '',
                supplierVersion: 0,
                workId: ''
            },

            //类型列表
            typeList: [],
            isIndeterminate: true,
            checkAll: true,
            //纳税类别列表
            payTaxesTypeList: [],
            oldEditData: {}, //编辑数据【保存原始的编辑数据，作为判断是否'变'的基础数据】
            //是否为境外单位的单选
            radio: '',
            orgId: '', //机构id
            orgName: '', //机构名称
            isSkip: false, //是否跳转
            isSubcontractorTypeKey: false, //判断外包方类型字段是否变更
            isLoad: false, //判断接口值回来没有
            // 验证
            rules: {
                // 统一社会信用代码
                creditCode: [
                    {
                        required: true,
                        validator: creditCodeVerification,
                        trigger: 'blur'
                    }
                ],
                //供应商名称
                supplierName: [
                    {
                        required: true,
                        message: '请输入分包商名称',
                        trigger: 'blur'
                    }
                ],
                //类型
                supplierTypeKey: [
                    { required: true, message: '请选择类型', trigger: 'change' }
                ],
                //法人代表
                deputy: [
                    {
                        required: true,
                        validator: isName,
                        trigger: 'blur'
                    }
                ],
                //电话
                contactTel: [
                    {
                        required: true,
                        validator: isPhone,
                        trigger: 'blur'
                    }
                ],
                //邮箱
                email: [
                    {  validator: isEmail, trigger: 'blur' }
                ],
                //邮编
                postCode: [
                    {
                        validator: isPostCode,
                        trigger: 'blur'
                    }
                ],
                //传真
                fax: [
                    {
                        validator: isFax,
                        trigger: 'blur'
                    }
                ],
                //纳税类别
                taxTypeValue: [
                    {
                        required: true,
                        message: '请选择纳税类别',
                        trigger: 'change'
                    }
                ],
                //是否为境外单位
                isAbroadUnit: [
                    {
                        required: true,
                        message: '请选择是否为境外单位',
                        trigger: 'change'
                    }
                ],
                // 注册地址
                registerAddInfo: [
                    {
                        required: true,
                        message: '请选择注册地址',
                        trigger: 'change'
                    }
                ]
            }
        }
    },
    computed: {
        // 判断状态
        statusLable () {
            return param => {
                const state = this.$store.state.equip.equipData.state
                const obj = state.find(x => x.value == param)
                if (obj !== undefined) {
                    return obj.label
                }
            }
        }
    },
    components: {
        SelectAddr
    },
    created () {
        this.billid = this.$route.query.billid
        let data = JSON.parse(localStorage.getItem('vuex'))
        this.formData.orgId = data.userInfo.orgInfo.orgId
        this.formData.orgName = data.userInfo.orgInfo.orgName
        this.getTypeData() //进入页面获取类型选择框数据
        this.getTreeData(data.userInfo) //获取用户所在机构
        this.getBasicData() //获取基础数据
    },
    methods: {
        ...mapMutations(['setPopConfirm']),
        //获取基本信息数据
        async getBasicData () {
            let res = await Supplier.factualOutsourcerBase({ id: this.billid })
            this.isLoad = true
            // 判断供应商类型不为空，则转为数组
            if (res.supplierTypeKey) {
                res.supplierTypeKey = res.supplierTypeKey.split(',')
                // 调用选择方法，将数据全选
                this.handleCheckedCitiesChange(res.supplierTypeKey)
            }
            // 判断供应商类型不为空，则转为数组
            if (res.supplierTypeValue) {
                res.supplierTypeValue = res.supplierTypeValue.split(',')
            }
            //境外单位转为字符串
            res.isAbroadUnit = res.isAbroadUnit + ''
            // 将请求回来的数据赋值
            this.formData = res
            // 将编辑id赋值给原单id，并把变更id置空
            this.formData.sourceId = res.id
            this.formData.id = ''
            // 将值存入老数组
            this.oldEditData = JSON.parse(JSON.stringify(res))
        },
        // 获取注册地址
        getAddrLabel (val) {
            this.formData.registerAdds = val
        },
        // 获取用户所在机构data
        async getTreeData (data) {
            const orgInfo = await getOrgById({
                orgId: data.orgInfo.orgId
            })
            // 如果类型是集团和分子公司，则管理机构为当前机构
            if (orgInfo.orgType == 1 || orgInfo.orgType == 2) {
                this.formData.manageOrgName = this.formData.orgName
                this.formData.manageOrgId = this.formData.orgId
            } else {
                // 否则通过机构id来查询父级机构，管理机构为父级机构
                const obj = await getOrgByParentId({
                    orgId: data.orgInfo.orgId
                })
                this.formData.manageOrgName = obj.parentId
                this.formData.manageOrgId = obj.parentName
            }
        },
        //获取供应商类型数据
        getTypeData () {
            call.getCredentialTree({ name: '外包方类型', id: '0' }).then(
                res => {
                    let id = ''
                    // 获取想要的类型id
                    res.map(item => {
                        if (item.kvKey == '供应商') {
                            id = item.kvId
                        }
                    })
                    call.getCredentialTree({
                        name: '外包方类型',
                        id: id
                    }).then(res => {
                        this.typeList = res
                    })
                }
            )
            call.getCredential('纳税类别').then(res => {
                this.payTaxesTypeList = res
            })
        },
        //保存按钮
        async save () {
            this.$refs.formData.validate(async valid => {
                if (valid) {
                    let data = JSON.parse(JSON.stringify(this.formData))
                    let newDate = await supplierChange.supplierChangeAdd(data)
                    if (newDate.code != 200) {
                        this.clientPop(
                            'info',
                            '保存成功！是否进行下一步操作？',
                            this.gocallback(newDate),
                            null,
                            this.cancelCallBack(newDate)
                        )
                        this.isSkip = false
                    }
                }
            })
        },
        // 保存成功继续回调
        gocallback (billid) {
            return () => {
                this.$router.push({
                    path: '/supplierbePutinstorageChangeEdit',
                    query: { billid }
                })
            }
        },
        // 保存成功，取消回调
        cancelCallBack (billid) {
            return () => {
                this.$router.push({
                    path: '/supplierbePutinstorage',
                    query: { billid }
                })
            }
        },
        //取消按钮
        cancel () {
            this.$router.push('/supplierbePutinstorage')
        },
        // 全选
        handleCheckAllChange (val) {
            this.formData.supplierTypeKey = val
                ? this.typeList.map(item => {
                    return item.kvKey
                })
                : []
            this.isIndeterminate = false
            // 循环拿到id
            this.typeList.map(item => {
                this.formData.supplierTypeValue.push(item.kvValue)
            })
        },
        //外包方类型选择
        handleCheckedCitiesChange (value) {
            this.formData.supplierTypeValue = []
            let checkedCount = value.length
            this.checkAll = checkedCount === this.typeList.length
            this.isIndeterminate =
                checkedCount > 0 && checkedCount < this.typeList.length
            // 通过类型判断是否是小规模纳税人
            value.forEach(item => {
                if (item == '其它' && checkedCount == 1) {
                    // 如果选择了其他类型，解锁小规模纳税人
                    this.payTaxesTypeList.map(item => {
                        if (item.kvValue == '1') {
                            return (item.disabled = false)
                        }
                    })
                } else {
                    // 如果选择了施工合作或者劳务分包，纳税类别为小规模纳税人，则重新赋值为一般纳税人
                    if (this.formData.taxTypeValue == '1') {
                        this.formData.taxTypeValue = '0'
                        this.payTaxesTypeList.map(item => {
                            if (this.formData.taxTypeValue == item.kvValue) {
                                this.formData.taxTypeName = item.kvKey
                            }
                        })
                    }
                    this.payTaxesTypeList.map(item => {
                        if (item.kvValue == '1') {
                            return (item.disabled = true)
                        }
                    })
                }
            })
            // 循环拿到id
            this.typeList.map(item => {
                value.map(Valitem => {
                    if (item.kvKey == Valitem) {
                        this.formData.supplierTypeValue.push(item.kvValue)
                    }
                })
            })
            /**
             * 先判断老数据是否有值，当老数据有值再判断外包方类型是否一样，不一样则显示'变'
             */
            if (this.formData && this.oldEditData.supplierTypeKey) {
                let data1 = this.formData.supplierTypeKey
                let data2 = this.oldEditData.supplierTypeKey
                if (JSON.stringify(data1) != JSON.stringify(data2)) {
                    this.isSubcontractorTypeKey = true
                } else {
                    this.isSubcontractorTypeKey = false
                }
            }
        },
        // 一般纳税人选择
        radioChange (row) {
            this.payTaxesTypeList.map(item => {
                if (row == item.kvKey) {
                    this.formData.taxTypeValue = item.kvValue
                }
            })
        }
    }
}
</script>

<style lang="scss" scoped>
.buttons {
    left: 0;
}
.e-form {
    margin-bottom: 80px;
    padding: 0 20px;
    .tabs-title::before {
        content: '';
        height: 22px;
        width: 8px;
        border-radius: 40px;
        background-color: #2e61d7;
        display: block;
        position: absolute;
        left: 20px;
        margin-right: 20px;
    }
}

.e-table {
    background: #fff;
}

.el-tab-pane {
    margin-left: -10px;
}
.img-style {
    width: 25px;
    height: 25px;
    margin: 0px 0px 4px 5px;
}
// 境外单位
::v-deep .clearPadding .vxe-cell {
    padding: 0;
}
::v-deep .clearPaddingLeft .vxe-cell {
    padding-left: 0px;
}
::v-deep {
    .main-el-switch {
        position: relative;
        .el-switch__core {
            height: 24px;
            border-radius: 12px;
            &:after {
                left: 4px;
                top: 3px;
            }
        }
        &.el-switch {
            &.is-checked {
                .el-switch__core {
                    &:after {
                        margin-left: -20px;
                        left: 100%;
                    }
                }
            }
        }
        &.is-checked {
            .el-switch__label--left {
                opacity: 0;
            }
            .el-switch__label--right {
                opacity: 1;
            }
        }
        .el-switch__label {
            position: absolute;
            top: 0;
        }
        .el-switch__label--left {
            right: 0;
            color: #999;
            z-index: 1;
            margin-right: 8px;
        }
        .el-switch__label--right {
            left: 0;
            color: #fff;
            opacity: 0;
            margin-left: 8px;
        }
    }
}
</style>
